<template>
  <div>
    <!-- 选项卡片 -->
    <!-- 引入全局组件 -->
    <Category :scene="scene"></Category>
    <!-- 展示卡片 -->
    <el-card style="margin: 10px 0px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr"
          >添加属性</el-button
        >
        <el-table border style="margin: 10px 0px" :data="attrArr" max-height="480">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <el-tag
                style="margin: 5px"
                v-for="(item) in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row}">
              <!-- 修改已有属性与属性值 -->
              <el-button
                type="primary"
                size="small"
                @click="updataAttr(row)"
                icon="edit"
              ></el-button>
              <el-popconfirm :title="`确定删除${row.attrName}`" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <!-- 展示添加属性与修改属性 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input 
              placeholder="请输入属性名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          @click="addAttrValue"
          icon="plus"
          :disabled="attrParams.attrName ? false : true"
          >添加属性值</el-button
        >
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-table border style="margin: 10px 0px" :data="attrParams.attrValueList">
          <el-table-column
            width="80px"
            type="index"
            align="center"
            label="序号"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <!-- row当前属性值对象 -->
            <template #="{ row, $index }">
              <el-input :ref="(vc:any)=>inputArr[$index]=vc" placeholder="请输入属性值名称" v-model="row.valueName" v-if="row.flag" @blur="toLook(row,$index)" :autofocus="true"></el-input>
              <div v-if="!row.flag" @click="toEdit(row,$index)">{{row.valueName}}</div>
            </template> 
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{$index}">
               <el-button type="primary" size="small" @click="attrParams.attrValueList.splice($index,1)" icon="delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" @click="save" :disabled="attrParams.attrValueList.length>0?false:true">保存</el-button>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import userCategoryStore from "@/store/modules/category";
let categoryStore = userCategoryStore();
//组合式API函数watch监听属性
import { watch, ref, reactive,nextTick,onBeforeMount } from "vue";
//引入已有属性值与属性值接口
import { reqAttr, reqAddOrUpdataAttr,delAttr } from "@/api/product/attr";
import type { AttrResponseDate, Attr,AttrValue } from "@/api/product/attr/type";
import { ElMessage } from "element-plus";
let attrParams = reactive<Attr>({
  attrName: "", //新增属性名称
  attrValueList: [
    //新增的属性值数组
  ],
  categoryId: "", //三级分类的ID
  categoryLevel: 3, //代表三级分类
}); 
//存储已有属性与属性值
let attrArr = ref<Attr[]>([]);

//定义卡片组件内容切换
let scene = ref<number>(0); //scence=0;scence=1,展示添加与修改属性结构
watch(
  () => categoryStore.c3Id,
  () => {
    //获取分类id(解构)
    getAttr();
  }
);
//获取已有属性与属性值的方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  //清空上次查询结果
  attrArr.value = [];
  if (!categoryStore.c3Id) return;
  let result: AttrResponseDate = await reqAttr(c1Id, c2Id, c3Id);
  console.log(result);
  if (result.code == 200) {
    attrArr.value = result.data;
  }
};
//添加属性按钮的回调
const addAttr = () => {
  scene.value = 1;
  attrParams.categoryId = categoryStore.c3Id;
};
//修改已有属性
const updataAttr = (row:Attr) => {
  scene.value = 1;
  //将已有属性值赋值给对象
  //Es6->Object.assign进行对象合并
  //存在浅拷贝（bug）
  // attrParams与数组对象指向同一个对象
  //当修改attrParams时数组对象也跟随改变
  //但是不保存，点击取消数据依旧改变，但是未向服务器发送请求
  // Object.assign(attrParams,row)

  //采取深拷贝的方法（1：lodush,2:JSON方法）
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
};
//取消按钮回调
const cancel = () => {
  scene.value = 0;
};
//定义新增属性对象

//添加属性值按钮的回调
const addAttrValue = () => {
  //点击添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: "",
    //控制每一个属性值编辑模式和查看模式切换
    flag:true,
  });
  //第一次添加数据input聚焦
  nextTick(()=>{
    //令数组最后一项聚焦
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  })
};
//保存按钮的回调
const save = async () => {
  //发送请求保存数据（成功/失败）
  //收集参数
  let result: any = await reqAddOrUpdataAttr(attrParams);
  if (result.code == 200) {
    //保存后清空数据
    Object.assign(attrParams, {
      attrName: "", //新增属性名称
      attrValueList: [
        //新增的属性值数组
      ],
      categoryId: "", //三级分类的ID
      categoryLevel: 3, //代表三级分类
    });
    //切换场景
    scene.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });

    //获取全部已有的属性与属性值；
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};
// //定义响应式数据控制编辑模式与查看模式(此方法当属性值过多时会影响其他值)
// let flag = ref<boolean>(true)
// //切换查看模式
// let toLook = ()=>{
//   flag.value = false
// }
// 切换编辑模式
let toEdit = (row:AttrValue,$index:number)=>{
  row.flag = true
  //nextTick当响应式数据发生变化,获取更新后的dom(组件实例)
  nextTick(()=>{
    inputArr.value[$index].focus();
  })
}

const toLook= (row:AttrValue,$index:number)=>{
  //非法情况判断1
  if(row.valueName.trim()==''){
    //当属入框为空时，删除数组为空的一项
    attrParams.attrValueList.splice($index,1)
    ElMessage({
      type:'error',
      message:'属性值不能为空' 
    })
    return ;
  }
  //非法情况2：属性值不能为空
  let repeat = attrParams.attrValueList.find((item)=>{
    if(item!=row){
      return item.valueName === row.valueName
    }
  })
  if(repeat){
    attrParams.attrValueList.splice($index,1)
    ElMessage({
      type:'error',
      message:'属性不能重复'
    })
    return
  }
  row.flag = false
}
//准备数组：将来存储对应的组件实例el-input
let inputArr = ref<any>([]);
// const handler = (element:any)=>{
//   //获取组件实例并存储在数组中
//   console.log(element)
//   input[$index] = element
// }
//删除属性值操作
const deleteAttr = async(attrId:number)=>{
  let result:any = await delAttr(attrId)
  console.log(result)
  //删除成功
  if(result.code === 200){
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    //获取一次已有属性与属性值
    getAttr();
  }else{
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }
}
//路由组件销毁清空数据
onBeforeMount(()=>{
  //清空分类仓库
  categoryStore.$reset()
})
</script>

<style scoped></style>
